# -*- coding: UTF-8 -*-
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models

from .validators import validate_screen_width, validate_username

#UserManager by author @ 2014/5/29
class UserManager(BaseUserManager):
    def _create_user(self, username, password, email, nickname, is_superuser, **extra_fields):
        """
        Creates and saves a User with the given information.
        Username and password are required.
        """
        now = timezone.now()
        if not (username and password):
            raise ValueError(u"Require username and password")
        email = self.normalize_email(email)
        user = self.model(
                username=username,
                email=email,
                is_active=True,
                is_superuser=is_superuser,
                last_login=now,
                **extra_fields
                )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, password, email=None, nickname=None, **extra_fields):
        return self._create_user(username, password, email, nickname, False, **extra_fields)

    def create_superuser(self, username, password, nickname=None, email=None, **extra_fields):
        return self._create_user(username, password, email, nickname, True, **extra_fields)

    """
    A simplified version of default User model
    Username, password and email are required. Other fields are optional.
    """

class ForumUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(
            u"username",
            max_length=30,
            unique=True,
            help_text=u"",
            validators=[validate_username]
            )
    nickname = models.CharField(
            u"nickname",
            max_length=30,
            blank=True
            )
    email = models.EmailField(u"email address", blank=True)
    is_active = models.BooleanField(
            u'is active',
            default=True
            )
    date_joined = models.DateTimeField("Created date", auto_now_add=True)
    date_updated = models.DateTimeField("Last edited", auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def get_full_name(self):
        """
        'full_name' here mean nickname. The method name is just meant to be consistent with django default.
        """
        return self.nickname

    def get_short_name(self):
        """
        'short_name' here mean username. The method name is just meant to be consistent with django default.
        """
        return self.username

    def email_user(self, subject, message, from_email=None, **kwargs):
        """
        Sends an email to this User
        """
        send_mail(subject, message, from_email, [self.email], **kwargs)

#ForumBackend(object) by author @ 2014/5/29
#Backend for user authentication
class ForumBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = ForumUser.objects.get(username__iexact=username)
            if user.check_password(password):
                return user
        except ForumUser.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return ForumUser.objects.get(pk=user_id)
        except ForumUser.DoesNotExist:
            return None
